use lapin::{
    message::DeliveryResult,
    options::{BasicAckOptions, BasicConsumeOptions, QueueDeclareOptions},
    types::FieldTable,
    Connection, ConnectionProperties,
};

#[tokio::main]
async fn main() {
    let url = "amqps://eaxyapkn:tRYdniZqsBBge5J3DXPFdFCqLQGew7FA@gerbil.rmq.cloudamqp.com/eaxyapkn";
    let options = ConnectionProperties::default()
        .with_executor(tokio_executor_trait::Tokio::current())
        .with_reactor(tokio_reactor_trait::Tokio);

    let connection = Connection::connect(url, options).await.unwrap();
    let channel = connection.create_channel().await.unwrap();
    let queue = channel
        .queue_declare(
            "hello-world",
            QueueDeclareOptions::default(),
            FieldTable::default(),
        )
        .await
        .unwrap();

    let consumer = channel
        .basic_consume(
            queue.name().as_str(),
            "hello-world-consummer",
            BasicConsumeOptions::default(),
            FieldTable::default(),
        )
        .await
        .unwrap();

    consumer.set_delegate(move |delivery: DeliveryResult| async move {
        let delivery = match delivery {
            Ok(Some(delivery)) => delivery,
            Ok(None) => return,
            Err(err) => {
                println!("Failed to consume queue message {}", err);
                return;
            }
        };

        let message = String::from_utf8_lossy(&delivery.data);
        println!("Received a message: {}", message);

        delivery.ack(BasicAckOptions::default()).await.unwrap();
    });
    connection.run().unwrap();
}
